package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.KaiDiDownLoader;
import com.spider.silence.utils.PropertiesUtil;

import java.util.LinkedList;

/**
 * Created by Administrator on 2017/1/9 0009.
 */
public class KaiDiDownLoaderPool {
    private static  KaiDiDownLoaderPool instance= new KaiDiDownLoaderPool();
    protected LinkedList<KaiDiDownLoader> pool = Lists.newLinkedList();

    private   KaiDiDownLoaderPool(){
        int initNum= Integer.parseInt(PropertiesUtil.getVal("KaiDi.DownLoader.Pool.initNum"));
        //KaiDiDownLoader downLoader =new KaiDiDownLoader();
        //downLoader.init();
        for(int i=0;i<initNum;i++){
            KaiDiDownLoader kaiDiDownLoader = new KaiDiDownLoader();
            pool.add( kaiDiDownLoader);
        }
    }

    public  static  KaiDiDownLoaderPool getInstance(){
        if(instance==null){
            instance=new  KaiDiDownLoaderPool();
        }
        return  instance;
    }
    public  void releaseDownLoader(KaiDiDownLoader downloader) {
        if (downloader != null) {
            synchronized (pool) {
                pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }

    public  KaiDiDownLoader fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            if(mills<=0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else {
                long future= System.currentTimeMillis()+mills;
                long remianing=mills;
                while (pool.isEmpty() && remianing >0){
                    pool.wait(remianing);
                    remianing=future-System.currentTimeMillis();
                }
                KaiDiDownLoader downLoader =null;
                if(!pool.isEmpty()){
                    downLoader=pool.removeFirst();
                }
                return downLoader;
            }
        }
    }

    /**
     * 清空池
     */
    public void empty(){
        pool=Lists.newLinkedList();
    }
}
